<template>
  <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="配置" name="field" />
      <el-tab-pane label="数据" name="data" />
      <el-tab-pane label="参数" name="location" />
    </el-tabs>
    <div class="field-box">
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        <el-form
          v-show="currentTab === 'field'"
          size="small"
          label-width="90px"
        >
          <el-form-item
            v-if="configData.layerName !== undefined"
            label="图层名称"
          >
            <el-input
              v-model="configData.layerName"
              placeholder="请输入图层名称"
            />
          </el-form-item>

          <el-form-item
            v-if="configData.chartOption.videoURL !== undefined"
            label="视频地址"
          >
            <el-input
              v-model="configData.chartOption.videoURL"
              placeholder="视频地址"
            />
          </el-form-item>

          <el-form-item
            v-if="configData.chartOption.replay !== undefined"
            label="循环播放"
          >
            <el-radio-group v-model="configData.chartOption.replay">
              <el-radio label="loop">是</el-radio>
              <el-radio label="">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="configData.chartOption.controls !== undefined"
            label="开启控制"
          >
            <el-switch v-model="configData.chartOption.controls" />
          </el-form-item>

          <el-form-item label="视频库">
            <el-button type="primary" @click="openStorage">视频库</el-button>
          </el-form-item>

          <el-form-item
            v-if="configData.chartOption.animate !== undefined"
            label="载入动画"
          >
            <el-select
              v-model="configData.chartOption.animate"
              placeholder="请选择"
            >
              <el-option
                v-for="item in animateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 表单属性 -->
        <el-form v-show="currentTab === 'data'" size="small" label-width="90px">
          <el-form-item v-if="" label="数据源类型">
            <el-select v-model="configData.chartOption.dataSourceType" placeholder="请选择">
                <el-option
                  v-for="item in dataSourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>

        <Databasewebsocket v-show="configData.chartOption.dataSourceType === 'websocket'" 
          :interfaceKey="configData.chartOption.interfaceKey" @getInterfaceKey="getInterfaceKey"></Databasewebsocket>
          
          <el-form-item v-show="configData.chartOption.dataSourceType === 'static'" label="静态数据值" prop="desc">
            <el-input type="textarea" :rows="20" v-model="staticDataValue"  @blur.prevent="changeStaticData()"></el-input>
          </el-form-item>

          <api-source v-show="configData.chartOption.dataSourceType === 'url'" 
            :interfaceUrl="interfaceUrl" 
            :requestMethod="configData.chartOption.requestMethod"
            :requestParameters="configData.chartOption.requestParameters"
            :token="configData.chartOption.token"
            :timeout="configData.chartOption.timeout"
            @changeApi="changeApi" ></api-source>

          <el-form-item label="通用处理" v-if="configData.chartOption.customData!==undefined">
            <el-button type="primary" @click="editData">编辑</el-button>
          </el-form-item>
        </el-form>
        <!-- 组件位置 -->
        <el-form
          v-show="currentTab === 'location'"
          size="small"
          label-width="90px"
        >
          <el-form-item label="X位置">
            <el-input-number
              v-model="configData.x"
              controls-position="right"
              :step="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="y位置">
            <el-input-number
              v-model="configData.y"
              controls-position="right"
              :step="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="宽度">
            <el-input-number
              v-model="configData.width"
              controls-position="right"
              :step="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="高度">
            <el-input-number
              v-model="configData.height"
              controls-position="right"
              :step="1"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <!-- 视频库对话框 -->
    <el-dialog
      title="视频库"
      :visible.sync="open"
      width="1000px"
      hight="600px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="视频名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入视频名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="所属模板">
          <el-input
            v-model="queryParams.viewTemplate"
            placeholder="请输入所属模板"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadOpenModel"
            >上传<i class="el-icon-upload el-icon--right"></i
          ></el-button>
          <!--
            <el-upload action="#" :show-file-list="false" :before-upload="beforeUpload" multiple>
            <el-button size="small">
              上传
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>-->
        </el-form-item>
      </el-form>

      <div style="overflow:auto; height:500px;">
        <ul
          class="background-images-ul"
          v-infinite-scroll="load"
          infinite-scroll-disabled="disabled"
        >
          <!-- <li v-for="item in uploadList" @click="selectImg(basePath + item.imagePath)">
              <img :src="basePath + item.imagePath" class="border_img">
              <label>{{ item.name }}</label>
            </li> -->
          <li
            v-for="item in uploadList"
            @click="selectVideo(item.imagePath)"
            style="overflow:hidden"
          >
            <video-gallery
              class="border_img"
              :customId="item.uploadId"
              :videoSrc="item.imagePath"
            ></video-gallery>
            <label :title="item.name">{{ item.name }}</label>
            <span
              title="删除"
              class="drawing-item-delete"
              @click.stop="deleteVideo(item.uploadId, item.imagePath)"
              ><i class="el-icon-delete"></i
            ></span>
          </li>
        </ul>
        <p v-if="loading" style="text-align: center;">加载中...</p>
        <p v-if="noMore" style="text-align: center;">没有更多了</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改数据大屏文件上传映射对话框 -->
    <el-dialog
      title="上传视频"
      :visible.sync="uploadOpen"
      width="500px"
      append-to-body
      v-loading="videoLoading"
    >
      <el-form
        ref="uploadForm"
        :model="uploadForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="是否公开" prop="isOpen">
          <el-radio-group v-model="uploadForm.isOpen">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属模板" prop="viewTemplate">
          <el-input
            v-model="uploadForm.viewTemplate"
            style="width: 360px"
            placeholder="请输入所属模板"
          />
        </el-form-item>

        <el-form-item label="上传">
          <!-- <el-upload
            class="upload-demo"
            drag
            action
            :http-request="httpRequest"
            :show-file-list="false" :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-upload"></i>
            </el-upload> -->
          <el-upload
            class="upload-demo"
            drag
            action
            multiple
            :http-request="httpRequest"
            :show-file-list="false"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :on-progress="uploadVideoProcess"
          >
            <i class="el-icon-upload"></i>
            <!-- <el-progress  v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="disabledFlag" @click="submitUpload"
          >提交</el-button
        >
        <el-button :disabled="disabledFlag" @click="cancelUpload"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="通用处理"
      v-if="dataOpen"
      :visible.sync="dataOpen"
      width="1000px"
      hight="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <data-editor
        :key="aceKey"
        @submitData="submitData"
        @cancelData="cancelData"
        :customData="configData.chartOption.customData==undefined?'':configData.chartOption.customData"
      ></data-editor>


    </el-dialog> 
  </div>
</template>

<script>
import { animateOptions } from "../../animate/animate";
import {
  listUpload,
  fileUpload,
  videoUpload,
  delUpload,
  videoDel
} from "@/api/tool/datav/fileUpload";
import VideoGallery from "@/views/tool/datav/components/config/VideoGallery";
import Interactionwebsocket from './chartDB/Interactionwebsocket'
import { dataSourceOptions, dataBaseOptions } from '../../ComponentsConfig'
import Databasewebsocket from './chartDB/Databasewebsocket'
import DataEditor from "@/views/tool/datav/components/config/runcode/DataEditor";
import ApiSource from './chartDB/ApiSource'

export default {
  components: {
    VideoGallery,
    Interactionwebsocket,
    Databasewebsocket,
    DataEditor,
    ApiSource
  },
  props: ["costomData"],
  data() {
    return {
      basePath: process.env.VUE_APP_BASE_API,
      currentTab: "field",
      configData: this.costomData,
      animateOptions,
      dataSourceOptions,
      dataBaseOptions,
      staticDataValue:
        this.costomData != null
          ? JSON.stringify(this.costomData.chartOption.staticDataValue)
          : "123",
      interfaceUrl:
        this.costomData.chartOption.interfaceURL != ""
          ? this.costomData.chartOption.interfaceURL
          : "",
      requestParameters:
        this.costomData.chartOption.requestParameters != ""
          ? this.costomData.chartOption.requestParameters
          : "",
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: "3",
        name: undefined,
        viewTemplate: undefined
      },
      rules: {
        isOpen: [
          { required: true, message: "是否公开不能为空", trigger: "blur" }
        ]
      },
      uploadList: [],
      total: -1,
      loading: false,
      uploadOpen: false,
      uploadForm: {
        isOpen:"0"
      },
      fileList: [],
      videoFlag: false,
      videoUploadPercent: 0,
      disabledFlag: false,
      videoLoading: false,
      aceKey:Math.random(),
      dataOpen:false,
    };
  },
  //页面加载完执行
  mounted() {},
  computed: {
    noMore() {
      if (this.total != -1) {
        return this.total == this.uploadList.length;
      } else {
        return false;
      }
    },
    disabled() {
      return this.loading || this.noMore;
    }
  },
  watch: {
    configData: {
      deep: true,
      handler(newVal) {
        // console.log("1=>", newVal);
        this.$emit("costom-change", newVal);
      }
    },
    costomData: {
      deep: true,
      handler(newVal) {
        this.configData = newVal;
        this.staticDataValue = JSON.stringify(
          newVal.chartOption.staticDataValue
        );
        this.interfaceUrl = newVal.chartOption.interfaceURL;
        this.requestParameters = newVal.chartOption.requestParameters;
      }
    }
  },
  methods: {
    changeStaticData() {
      //如果是静态数据就给staticDataValue赋值
      if (this.configData.chartOption.isStaticData == true) {
        //this.configData.staticDataValue = JSON.parse(this.staticDataValue);
        this.$set(
          this.configData.chartOption,
          "staticDataValue",
          JSON.parse(this.staticDataValue)
        );
      } else {
        //this.configData.interfaceURL = this.staticDataValue;
        this.$set(
          this.configData.chartOption,
          "staticDataValue",
          this.staticDataValue
        );
      }
    },
    changeInterfaceUrl() {
      this.$set(this.configData.chartOption, "interfaceURL", this.interfaceUrl);
    },
    changeRequestParameters() {
      this.$set(
        this.configData.chartOption,
        "requestParameters",
        this.requestParameters
      );
    },
    openStorage() {
      this.total = -1;
      this.uploadList = [];
      this.queryParams.pageNum = 1;
      this.open = true;
      this.load();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    handleQuery() {
      this.total = -1;
      this.uploadList = [];
      this.queryParams.pageNum = 1;
      this.open = true;
      this.load();
    },
    load() {
      this.loading = true;
      listUpload(this.queryParams).then(response => {
        this.uploadList = this.uploadList.concat(response.rows);
        this.total = response.total;
        this.queryParams.pageNum++;
        this.loading = false;
      });
    },
    selectVideo(item) {
      this.$set(this.configData.chartOption, "videoURL", item);
      //this.configData.chartOption.border = item;
      this.open = false;
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }
    },
    //取消上传
    cancelUpload() {
      this.uploadOpen = false;
    },
    uploadOpenModel() {
      this.uploadOpen = true;
    },

    beforeUploadVideo(file) {
      const isLt10M = file.size / 1024 / 1024 < 500;
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb"
        ].indexOf(file.type) == -1
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传视频大小不能超过500MB哦!");
        return false;
      }
    },

    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0);
    },
    handleVideoSuccess(res, file) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      if (res.status == 200) {
        // this.videoForm.videoUploadId = res.data.uploadId;
        // this.videoForm.Video = res.data.uploadUrl;
      } else {
        this.$message.error("视频上传失败，请重新上传！");
      }
    },

    //自定义上传,重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到fileList数组中
    httpRequest(option) {
      this.fileList.push(option);

      this.msgSuccess("成功上传至浏览器缓存");
    },
    submitUpload() {
      this.$refs["uploadForm"].validate(valid => {
        if (this.fileList.length == 0) {
          this.$message.error("请上传文件!");
          return false;
        }
        if (valid) {
          this.videoLoading = true;
          this.disabledFlag = true;

          // 使用form表单的数据格式
          let paramsData = new FormData();
          // 将上传文件数组依次添加到参数paramsData中
          this.fileList.forEach((it, index) => {
            //paramsData.append(`files[${index}]`, it.file)
            paramsData.append("file", it.file); // 因为要上传多个文件，所以需要遍历一下才行
          });
          // 将表单数据添加到参数paramsData中
          paramsData.append("isOpen", this.uploadForm.isOpen);
          paramsData.append("viewTemplate", this.uploadForm.viewTemplate);
          paramsData.append("type", "3");

          // 表单数据和文件一起上传,调用后端接口
          videoUpload(paramsData).then(response => {
            //  console.log(response);
            if (response.code == 200) {
              this.disabledFlag = false;
              this.videoLoading = false;
              this.uploadOpen = false;
              this.fileList = [];
              this.uploadForm.isOpen = "0";
              this.uploadForm.viewTemplate = undefined;
              this.msgSuccess("上传成功");
              //重新加载上传数据
              this.uploadList = [];
              this.queryParams.pageNum = 1;
              this.load();
            }
          });
        }
      });
    },
    deleteVideo(uploadId, fileUrl) {
      this.$confirm("是否确认删除该视频?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          videoDel(uploadId).then(response => {
            if (response.code === 200) {
              this.msgSuccess("删除成功");
              //重新加载上传数据
              this.uploadList = [];
              this.queryParams.pageNum = 1;
              this.load();
            } else {
              this.msgError(response.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除操作"
          });
        });
    },
    pageCount(totalnum, limit) {
      return totalnum > 0
        ? totalnum < limit
          ? 1
          : totalnum % limit
          ? parseInt(totalnum / limit) + 1
          : totalnum / limit
        : 0;
    },
    getInterfaceKey(val){
      this.$set(this.configData.chartOption, 'interfaceKey', val);
    },
    changeApi(val){
      if(val.type == "interfaceUrl"){
        this.$set(this.configData.chartOption, 'interfaceURL', val.arr);
      }else if(val.type == "requestParameters"){
        this.$set(this.configData.chartOption, 'requestParameters', val.arr);
      }else if(val.type == "requestMethod"){
        this.$set(this.configData.chartOption, 'requestMethod', val.arr);
      }else if(val.type == "token"){
        this.$set(this.configData.chartOption, 'token', val.arr);
      }else if(val.type == "timeout"){
        this.$set(this.configData.chartOption, 'timeout', val.arr);
      }
    },
    editData(){
      this.dataOpen = true;
    },
    cancelData(){
      this.dataOpen = false;
    },
    submitData(data){
      this.$set(this.configData.chartOption, 'customData', data);
      this.dataOpen = false;
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .center-tabs .el-tabs__item {
  width: 33%;
  text-align: center;
}
.background-images-ul {
  margin-bottom: 20px;
}
.background-images-ul li {
  margin: 2px;
  display: inline-block;
  width: 200px;
  line-height: 25px;
  padding: 20px;
  border: 1px solid #e2e2e2;
  font-size: 14px;
  text-align: center;
  color: #666;
  transition: all 0.3s;
  -webkit-transition: all 0.3s;
  cursor: pointer;
  position: relative;
  &:hover {
    & > .drawing-item-delete {
      display: initial;
    }
  }
  & > .drawing-item-copy,
  & > .drawing-item-delete {
    display: none;
    position: absolute;
    top: 0px;
    right: 15px;
    width: 22px;
    height: 22px;
    line-height: 20px;
    text-align: center;
    border-radius: 50%;
    font-size: 12px;
    border: 1px solid;
    cursor: pointer;
    z-index: 1;
  }
  & > .drawing-item-delete {
    right: 0px;
    border-color: #f56c6c;
    color: #f56c6c;
    background: #fff;
    &:hover {
      background: #f56c6c;
      color: #fff;
    }
  }
}
.border_img {
  width: 160px;
  height: 90px;
}
.background-images-ul label {
  display: inline-block;
  width: 160px;
  color: #dbeeff;
  overflow: hidden;
}
.background-images-ul label {
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>